﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ChatServerApplication
{
    class ServerClientHandling
    {
        private Socket sock;
        ClientObject cl;

        public ServerClientHandling(Socket sock) { this.sock = sock; }

        public void Run()
        {
            ChatServerApplication.dle.Invoke("Client connected with: " + sock.RemoteEndPoint.ToString());
            String request = getContent();

            switch (request)
            {
                case "LOGIN":
                    executeLogin();
                    break;
                default:
                    break;
            }
        }

        private void executeLogin()
        {
            byte[] data = "ACK".ToByteArray();
            NetworkStream networkStream = new NetworkStream(sock);
            networkStream.Write(data, 0, data.Length);
            Thread.Sleep(1000);
            data = new byte[1024];
            String temp1 = getContent();
            String[] temp = data.ToAsciiString("|");
            if (temp[0].Equals("ACK"))
            {
                cl = new ClientObject(temp[1], temp[2], sock.RemoteEndPoint.ToString());
                ChatServerApplication.duu.Invoke(cl);
            }
        }

        private String getContent()
        {
            String content = "";
            Thread.Sleep(10);
            while (sock.Available > 0)
            {
                int bytes = sock.Available;
                byte[] buffer = new byte[bytes];
                sock.Receive(buffer, bytes, SocketFlags.None);
                content += Encoding.UTF8.GetString(buffer);
                Thread.Sleep(10);
            }
            return content;
        }
    }
}
